package cn.xjt.demo03;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * 线程的第三种方式
 * @author xujiangtao
 * @create 2020-07-31-18:55
 */
public class testCallable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        dThread d = new dThread("https://i0.hdslb.com/bfs/sycp/creative_img/202007/c522b6de0506edaa1098703aaf684a2e.jpg","宇航员.jpg");
        dThread d2 = new dThread("https://t9.baidu.com/it/u=583874135,70653437&fm=79&app=86&size=h300&n=0&g=4n&f=jpeg?sec=1596778007&t=6b01deba697e5f06943396100bd58738","动物.jpg");
        dThread d3=new dThread("https://t7.baidu.com/it/u=3616242789,1098670747&fm=79&app=86&size=h300&n=0&g=4n&f=jpeg?sec=1596778007&t=e11ba092f9d1dcc4199a869481fe3e4d","美女.jpg");
        ExecutorService t = Executors.newFixedThreadPool(3);        //开启服务

        //提交执行
        Future<Boolean> result1=t.submit(d);
        Future<Boolean> result2=t.submit(d2);
        Future<Boolean> result3=t.submit(d3);
        //返回结果
        Boolean res = result1.get();
        Boolean res1=result2.get();
        Boolean res2 = result3.get();
        //关闭服务
        t.shutdownNow();
    }

}
class dThread implements Callable<Boolean> {
    private String url;
    private String name;
    public dThread(String url,String name)
    {
        this.url=url;
        this.name= name;
    }
    @Override
    public Boolean call() {
        Download d = new Download();
        System.out.println(Thread.currentThread().getName()+"开始下载");
        d.imageDownload(url,name);
        return Thread.currentThread().isAlive();
    }
}

/**
 * 下载器
 */
class Download{
    public void imageDownload(String url,String name)
    {
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常了，下载方法出现问题");
        }
    }
}

